package taxexporter.util;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.jdt.internal.core.JavaProject;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.ISelectionService;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.ide.IDE;
import org.eclipse.ui.internal.Workbench;

/**
 * 工具单元
 * 
 * @author sunny
 *
 */
public class Util {
	private static final int BUFFER_SIZE = 512;

	public static IProject getFirstProject() {
		IWorkspace workspace = ResourcesPlugin.getWorkspace();
		IWorkspaceRoot root = workspace.getRoot();
		IProject[] projects = root.getProjects();
		if ((projects != null) && (projects.length > 0)) {
			for (IProject project : projects) {
				if (project.isOpen()) {
					Path path = new Path("/src/main/webapp/WEB-INF/web.xml");
					IFile xml = project.getFile(path);
					if (xml.exists()) {
						return project;
					}
				}
			}
		}
		return null;
	}

	public static IProject getCurrentProject() {
		IProject currentProject = null;

		ISelectionService selectionService = Workbench.getInstance().getActiveWorkbenchWindow().getSelectionService();
		ISelection selection = selectionService.getSelection("org.eclipse.ui.navigator.ProjectExplorer");
		if ((selection == null) || (selection.isEmpty())) {
			selection = selectionService.getSelection("org.eclipse.jdt.ui.PackageExplorer");
		}
		if ((selection == null) || (selection.isEmpty())) {
			selection = selectionService.getSelection("org.eclipse.ui.views.ResourceNavigator");
		}
		if ((selection == null) || (selection.isEmpty())) {
			return getFirstProject();
		}
		Object element = ((IStructuredSelection) selection).getFirstElement();

		if ((element instanceof IResource)) {
			currentProject = ((IResource) element).getProject();
		}

		if (currentProject == null) {
			if (element instanceof JavaProject) {
				currentProject = ((JavaProject) element).getProject();
			}
		}

		return currentProject;
	}

	public static IFile createFile(IProject currentProj, String path, String content, boolean replace)
			throws IOException, CoreException {
		IFile result = null;
		InputStream ibuffer = null;
		try {
			ibuffer = new ByteArrayInputStream(content.getBytes(Consts.DEFAULT_ENCODE));
			if (currentProj != null) {
				result = currentProj.getFile(path);
				if (result.exists()) {
					if (!replace)
						return result;
					result.setContents(ibuffer, IResource.NONE, null);
				} else {
					IFolder folder = (IFolder) result.getParent();
					if (!folder.exists())
						folder.create(IResource.FORCE, true, null);
					result.create(ibuffer, true, null);
				}
			}
		} finally {
			if (ibuffer != null)
				ibuffer.close();
		}
		return result;
	}

	public static void copy(String from, String to) throws IOException {
		FileInputStream in = new FileInputStream(from);
		FileOutputStream out = new FileOutputStream(to);
		byte[] buffer = new byte[BUFFER_SIZE];
		int readed = 0;
		while ((readed = in.read(buffer, 0, BUFFER_SIZE)) >= 0) {
			out.write(buffer, 0, readed);
		}
		out.flush();
		out.close();
		in.close();
	}

	/**
	 * 文件转字符串
	 * 
	 * @param filePath
	 * @param encode
	 * @return
	 * @throws IOException
	 */
	public static String file2Str(String filePath, String encode) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), encode));
		StringBuilder sb = new StringBuilder();
		String line;
		while ((line = br.readLine()) != null) {
			sb.append(line).append("\n");
		}
		br.close();
		return sb.toString();
	}

	/**
	 * 字符串转文件
	 * 
	 * @param filePath
	 * @param encode
	 * @param content
	 * @throws IOException
	 */
	public static void str2File(String filePath, String encode, String content) throws IOException {
		byte[] buffer = content.getBytes(encode);
		FileOutputStream fos = new FileOutputStream(filePath);
		fos.write(buffer);
		fos.flush();
		fos.close();
	}

	public static void openView(String viewId) {
		try {
			PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().showView(viewId);
		} catch (PartInitException e) {
			e.printStackTrace();
		}
	}

	public static void openSource(String path) {
		IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
		IPath iPath = new Path(path);
		IFile file = getCurrentProject().getFile(iPath);
		try {
			IDE.openEditor(page, file);
		} catch (PartInitException e) {
			e.printStackTrace();
		}
	}
}
